# Copyright(C) 2023. Huawei Technologies Co.,Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import time
import multiprocessing
from datetime import datetime
import argparse

import numpy as np
import websockets
import cv2
from pydub import AudioSegment

from pipeline import DigitalHumanPipeline


parser = argparse.ArgumentParser(description="常量配置")

parser.add_argument("--server_addr", type=str, default="0.0.0.0", help="服务器地址")
parser.add_argument("--recv_port", type=int, default=8763, help="接收端口号")
parser.add_argument("--send_port", type=int, default=8764, help="发送端口号")
parser.add_argument("--sample_rate", type=int, default=16000, help="采样率")
parser.add_argument("--fps", type=int, default=25, help="帧率")

args = parser.parse_args()

# 将命令行参数赋值给常量
SERVER_ADDR = args.server_addr
RECV_PORT = args.recv_port
SEND_PORT = args.send_port
SAMPLE_RATE = args.sample_rate
FPS = args.fps

CLIENT_ID = "6688"

pipeline_input_queue = multiprocessing.Queue()
pipeline_output_queue = multiprocessing.Queue()


async def send(websocket):
    wav_frame_num = SAMPLE_RATE // FPS
    while True:
        try:
            (
                imgs,
                speech_array,
                sentence,
                is_end,
            ) = pipeline_output_queue.get()
            speech_array = speech_array * 32767  # int16最大值为32767，归一化
            speech_array = speech_array.astype(np.int16)
            await websocket.send(sentence)
            image_num = len(imgs)
            await websocket.send("{}".format(image_num))
            for i in range(image_num):
                _, img_encode = cv2.imencode(".jpg", imgs[i])
                img_data = img_encode.tobytes()
                await websocket.send(img_data)
                if i == image_num - 1:
                    await websocket.send(speech_array[i * wav_frame_num :].tobytes())
                else:
                    await websocket.send(
                        speech_array[
                            i * wav_frame_num : (i + 1) * wav_frame_num
                        ].tobytes()
                    )

        except Exception as e:
            print("[ERROR] websocket receive Exception{}".format(e))
            await websocket.close()


async def receive(websocket):
    while True:
        try:
            data = await websocket.recv()
            await websocket.send("hello")
            audio_data_numpy = np.frombuffer(data, dtype=np.int16)
            pipeline_input_queue.put(audio_data_numpy)

        except Exception as e:
            print("[ERROR] websocket receive Exception{}".format(e))
            break


async def send_coroutine(websocket, path):
    print(f"[SERVER] Connection from {id(websocket)}")
    await asyncio.get_event_loop().create_task(send(websocket))
    print("send_coroutine wait...")


async def recv_coroutine(websocket, path):
    print(f"[SERVER] Connection from {id(websocket)}")
    await asyncio.get_event_loop().create_task(receive(websocket))
    print("recv_coroutine wait...")


def send_process():
    print(f"send_process {SERVER_ADDR}:{RECV_PORT} websocket...")
    start_server = websockets.serve(
        send_coroutine, SERVER_ADDR, RECV_PORT, ping_interval=None
    )
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()


def recv_process():
    print(f"recv_process {SERVER_ADDR}:{SEND_PORT} websocket...")
    start_server = websockets.serve(
        recv_coroutine, SERVER_ADDR, SEND_PORT, ping_interval=None
    )
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()


def start_pipeline(client_id, inque, outque):
    adh_pipeline = DigitalHumanPipeline(client_id, inque, outque)
    adh_pipeline.run_pipeline()


if __name__ == "__main__":
    recv_pro = multiprocessing.Process(target=recv_process)
    recv_pro.start()

    send_pro = multiprocessing.Process(target=send_process)
    send_pro.start()

    pipeline_pro = multiprocessing.Process(
        target=start_pipeline,
        args=(
            CLIENT_ID,
            pipeline_input_queue,
            pipeline_output_queue,
        ),
    )
    pipeline_pro.start()
